import { useStore } from '@/store';
import { delStorage, TOKEN, USER_INFO } from '@/utils/storage';

// 不检验防抖列表
const pass = [];
// 缓存请求
let urls = [];
let isRelogin = { show: false };

const request = ({ url, method, data, isToken = true, header }) => {
  const store = useStore();

  const path = `${url}?p=${JSON.stringify(data)}`;
  const index = urls.indexOf(path);
  if (index >= 0) {
    urls.splice(index, 1);
    console.log('请求中...');
    uni.showToast({ title: '数据请求中...', icon: 'error' }).then(() => {});
    return;
  } else if (!pass.includes(url)) {
    urls.push(path);
  }

  return new Promise((resolve, reject) => {
    let headers = { ...header };
    if (isToken) {
      if (store.token && store.token !== '') {
        headers['Authorization'] = store.token;
      } else {
        reject('未登录');
        urls = [];
        if (!isRelogin.show) {
          isRelogin.show = true;
          uni.showModal({
            title: '登录提示',
            content: '当前未登录，是否返回登录页面？',
            success: function (res) {
              isRelogin.show = false;
              if (res.confirm) {
                delStorage(TOKEN);
                delStorage(USER_INFO);
                uni.reLaunch({ url: '/pages/login/login' }).then(() => {});
              }
            },
            fail: function () {
              isRelogin.show = false;
            }
          });
        }
        return;
      }
    }
    uni.request({
      url: store.baseUrl + url,
      method: method,
      data: data,
      header: headers,
      success: ({ data }) => {
        if (data.code === 200) {
          resolve(data);
        } else if (data.code === 401) {
          reject(data);
          if (!isRelogin.show) {
            isRelogin.show = true;
            uni.showModal({
              title: '登录失效',
              content: '登录状态已过期，是否返回登录页面？',
              success: function (res) {
                isRelogin.show = false;
                if (res.confirm) {
                  delStorage(TOKEN);
                  delStorage(USER_INFO);
                  uni.reLaunch({ url: '/pages/login/login' }).then(() => {});
                }
              },
              fail: function () {
                isRelogin.show = false;
              }
            });
          }
        } else {
          reject(data);
        }
      },
      fail: () => {
        reject();
      },
      complete: () => {
        const index = urls.indexOf(path);
        if (index >= 0) {
          urls.splice(index, 1);
        }
      }
    });
  });
};

//上传
const uploadRequest = ({ url, imgUrl }) => {
  const { baseUrl, token } = useStore();

  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: baseUrl + url,
      filePath: imgUrl,
      name: 'file',
      formData: {
        uploadType: 0
      },
      header: {
        Authorization: token
      },
      success: res => {
        const timer = setTimeout(() => {
          resolve(res.data);
          clearTimeout(timer);
        }, 50);
      },
      fail: res => {
        reject(res);
      }
    });
  });
};

// 下载
const downloadRequest = ({ url }) => {
  return new Promise((resolve, reject) => {
    uni.downloadFile({
      url: url,
      success: res => {
        if (res.statusCode === 200) {
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: err => {
        reject(err);
      }
    });
  });
};

export { request, uploadRequest, downloadRequest };
